<?php
namespace app\admin\controller\customer;

use app\common\model\SystemCustomer;
use library\Controller;
use think\Db;

/**
 * 公海客户
 * Class Opensea
 * @package app\admin\controller\customer
 */
class Opensea extends Controller
{
     /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SystemCustomer';	
	
    /**
     * 客户列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '公海客户';
        $where = [];            
		$where[] = ['is_deleted','eq',0];
		$where[] = ['charger','eq',0];
		$where[] = ['status','eq',2];
		$dep_user =  dep_users(1);
		$this->charger_op = assemble_op([''=>'-- 全部负责人 --'], $dep_user);   
		$this->country_op = assemble_op([''=>'-- 全部国家 --'], get_all_options('country'));   
        $this->source_type_op = assemble_op([''=>'-- 全部来源渠道 --'], get_all_options('source_type'));
        $this->post_type_op = assemble_op([''=>'-- 全部客户类型 --'], get_all_options('post_type'));
        $this->intention_level_op = assemble_op([''=>'-- 全部意向程度 --'], SystemCustomer::INTENTION_LEVEL);
			   
		$query = $this->_query($this->table)->like('unique,company_name')->equal('charger,country,source_type,intention_level,post_type');    
		$query->where($where)->order('id desc')->dateBetween('create_at,last_follow_at,first_contact_at,last_sea_at')->page();       
    }
    
    
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {
    	$country = get_all_options('country');
    	$source_type = get_all_options('source_type');
    	$post_type = get_all_options('post_type');
    	$intention_level = SystemCustomer::INTENTION_LEVEL;
    	foreach ($data as &$vo) {       	     	
			$vo['source_type_cn'] = $source_type[$vo['source_type']];
			$vo['intention_level_cn'] = $intention_level[$vo['intention_level']];
			$vo['post_type_cn'] = $post_type[$vo['post_type']];
			$vo['country_cn'] = $country[$vo['country']];
        }		
    }
    
    /**
     * 表单数据处理
     * @param array $data
     * @auth true
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {	
            $where = [['company_name', 'eq', $data['company_name']]];
            if (!empty($data['id'])) $where[] = ['id ', 'neq', $data['id']];
            if (Db::name($this->table)->where($where)->count() > 0) {
                $this->error('公司已存在，请更改公司名称');
            }			           
			  
        }else{
        				
        	$this->chargers = dep_users(1); 
        	$this->intention_level = SystemCustomer::INTENTION_LEVEL;
			if(!empty($data['id'])){				
				$this->countrys = get_all_options('country');
				$this->source_types = get_all_options('source_type');
				$this->post_type = get_all_options('post_type');
				$this->transactions = get_all_options('transaction');
			}else{
				$this->countrys = get_normal_options('country');
				$this->source_types = get_normal_options('source_type');
				$this->post_type = get_normal_options('post_type');
				$this->transactions = get_normal_options('transaction');				
			}
        	if($data){
        		$this->oplog = readoplog($data['id'],$this->table);
        	}     	
        }
    }
    
  
    /**
     * 查看客户
     * @auth true
     */
    public function browse()
    {  	
    	$this->title = '查看客户'; 	
    	$this->_form($this->table, 'f_browse');   	 	      
    }
	
	
	/**
     * 领取客户
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function receive()
    {
        $id = $this->request->param('id');
		if(empty($id) || !$id){
			$this->error('参数错误');
		}
		$customer = Db::name($this->table)->where(['id'=>$id])->find();
		if($customer['status'] != 2){
			$this->error('客户状态异常，无法领取');
		}
		//查询今日领取上限
		$charger = get_charger();
		$today = date('Y-m-d',time());
		$receive_num = Db::name('system_customer_shifts')->where(['charger'=>$charger,'add_at'=>$today,'type'=>2])->count();
		if($receive_num >= get_customer_config(1,'pull_day_max')){
			$this->error('今日领取已超上限，无法领取');
		}
			
		Db::startTrans();
        try {           	
		    $end_at = get_futuredate(get_customer_config(1,'expire_day'));        
            Db::name($this->table)->where(['id'=>$id])->update(['charger'=>$charger,'status'=>1,'gain_at'=>$today,'end_at'=>$end_at]);
            
            //写入客户转移记录表
			$create_at = date('Y-m-d H:i:s',time());
			$data = [
				'customer_id' => $customer['id'],
				'charger' => $charger,
				'type' => 2,
				'describe'=>'主动领取公海客户',
				'add_at' => $today,
				'created_at'=>$create_at,
				'updated_at'=>$create_at,
			];
			Db::name('system_customer_shifts')->insert($data);
			
            Db::commit();
            sysoplog('公海客户', '领取'.$customer['unique'].'成功');
			operatelog($id,$this->table,'领取了客户');
            $this->success('领取成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('领取失败，请重试');
        }
		
    }
	
 
    /**
     * 导出客户
     * @auth true
     */
//  public function export()
//  {  	
//  	$data = $this->request->param();
//  	$ids = explode(',', $data['id']);
//  	$list = CompanyService::export_company($ids);
//  	toexcel($list['filename'],$list['titles'],$list['list']);   	 	      
//  }
    

}
